#include "classifierproductmodel.h"
#include "database/dbtabclassifierproduct.h"

ClassifierProductModel::ClassifierProductModel(int colCnt,const QString& showName,QObject* parent) : QAbstractListModel(parent),
    mColumnCount(colCnt),mColumnName(showName)
{
    mQuery = new DataBaseQuery();
    mTabName = DBTabClassifierProduct::TAB_NAME;
}

ClassifierProductModel::~ClassifierProductModel()
{
    delete mQuery;
}

bool ClassifierProductModel::submit()
{
    beginResetModel();
    QStringList keyList;
    keyList<<mColumnName<<DBTabClassifierProduct::_BARCODE<<DBTabClassifierProduct::_R1_LOW<<DBTabClassifierProduct::_R1_HI
            <<DBTabClassifierProduct::_R2_LOW<<DBTabClassifierProduct::_R2_HI<<DBTabClassifierProduct::_R3_LOW<<DBTabClassifierProduct::_R3_HI
            <<DBTabClassifierProduct::_R4_LOW<<DBTabClassifierProduct::_R4_HI<<DBTabClassifierProduct::_R5_LOW<<DBTabClassifierProduct::_R5_HI
            <<DBTabClassifierProduct::_R6_LOW<<DBTabClassifierProduct::_R6_HI<<DBTabClassifierProduct::_R7_LOW<<DBTabClassifierProduct::_R7_HI
            <<DBTabClassifierProduct::_R8_LOW<<DBTabClassifierProduct::_R8_HI<<DBTabClassifierProduct::_R9_LOW<<DBTabClassifierProduct::_R9_HI
            <<DBTabClassifierProduct::_R10_LOW<<DBTabClassifierProduct::_R10_HI<<DBTabClassifierProduct::_R11_LOW<<DBTabClassifierProduct::_R11_HI
            <<DBTabClassifierProduct::_R12_LOW<<DBTabClassifierProduct::_R12_HI;

    mQuery->selectTable(DBTabClassifierProduct::TAB_NAME,&keyList);
    endResetModel();
    mDataCount = mQuery->size();
    return true;
}

bool ClassifierProductModel::submitFilter(const QString &str)
{
    beginResetModel();
    mQuery->exec("select DISTINCT "+mColumnName + " from " + mTabName
                     + " where " + QString(DBTabClassifierProduct::_NAME) + " LIKE \""+ str +"%\"");
    endResetModel();
    mDataCount = mQuery->size();
    return true;
}


int ClassifierProductModel::rowCount(const QModelIndex &parent) const
{
    return (mDataCount+mColumnCount-1)/mColumnCount;
}

int ClassifierProductModel::columnCount(const QModelIndex &parent) const
{
    return mColumnCount;
}

QVariant ClassifierProductModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
    {
        return QVariant();
    }

    if(mQuery->seek(index.row()*mColumnCount+index.column()))
    {
        return mQuery->value(role-Qt::UserRole);
    }
    else
    {
        return QVariant();
    }
    return QVariant();
}

